/*
 * importer: () => import("@/xxx/xxx.[vue,png...]")
 *  */
export function getImporterAsync(importer) {
  if (typeof importer !== "function") {
    return Promise.reject();
  }
  return new Promise((resolve) => {
    (async () => {
      const file = await importer().catch((error) => {
        console.error(error), resolve();
      });
      resolve(file ? file.default || file : undefined);
    })();
  });
}

/*
 * importer: () => import("@/xxx/xxx.png")
 * width: 图片 width, 可选，只会影响 img.width 的值，naturalWidth 不受影响
 * height: 图片 height, 可选，只会影响 img.height 的值，naturalHeight 不受影响
 *  */
export function getImageAsync(importer, width, height) {
  return new Promise((resolve) => {
    (async () => {
      const url = await getImporterAsync(importer);
      const img = new Image(width, height);
      img.onload = () => resolve(img);
      img.src = url;
    })();
  });
}

// 将blob转换为file
export function blobToFile(blob, fileName) {
  const type = blob.type;
  const name = fileName + "." + type.replace(/([a-z]+\/)/, "");
  return new window.File([blob], name, { type });
}

export function fileToBlob(file, type) {
  return new Blob([file], { type: file.type || type || "application/*" });
}
// base64转换为blob
export function dataURLtoBlob(dataUrl) {
  const arr = dataUrl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const str = atob(arr[1]);
  let len = str.length;
  const u8arr = new Uint8Array(len);
  while (len--) {
    u8arr[len] = str.charCodeAt(len);
  }
  return new window.Blob([u8arr], { type: mime });
}

export function dataURLtoFile(dataUrl, fileName) {
  return blobToFile(dataURLtoBlob(dataUrl), fileName);
}

export function saveFile(url, name) {
  const a = document.createElement("a");
  a.download = name;
  a.href = url;
  a.click();
}

export function saveBlobFile(blob, name) {
  const url = window.URL.createObjectURL(blob);
  saveFile(url, name);
  window.URL.revokeObjectURL(url);
}

export function download(url, name) {
  const xhr = new window.XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = () => saveBlobFile(xhr.response, name);
  xhr.send();
}
